import { login, logout } from '@/api/user'
import { setToken, getToken, clearAllStorage } from '@/libs/util'

// 获取用户信息
function getUserInfo () {
    return JSON.parse(window.localStorage.getItem('userinfo')) || {}
}

// 设置用户信息
function setUserInfo (info) {
    window.localStorage.setItem('userinfo', JSON.stringify(info))
}

/**
 * 根据key修改用户信息
 * @param {String} key
 * @param {String} value 值
 */
function setUserInfoByKey (key, value) {
    let userInfo = getUserInfo()
    userInfo[key] = value
    setUserInfo(userInfo)
}

const userInfo = getUserInfo()

export default {
    state: {
        userName: userInfo.userName || '',
        userId: userInfo.userId || '',
        token: getToken(),
        roleType: userInfo.roleType || ''
    },
    mutations: {
        setUserInfo (state, info) {
            Object.keys(info).forEach(key => {
                state[key] !== undefined && (state[key] = info[key])
            })
            setUserInfo(info)
        },
        setUserId (state, id) {
            state.userId = id
            setUserInfoByKey('userId', id)
        },
        setUserName (state, name) {
            state.userName = name
            setUserInfoByKey('userName', name)
        },
        setToken (state, token) {
            state.token = token
            setToken(token)
        }
    },
    actions: {
    // 登录
        handleLogin ({ commit }, info) {
            return new Promise((resolve, reject) => {
                login(info).then(res => {
                    if (res.data.code == '0000') {
                        const data = res.data
                        commit('setToken', data.data.token)
                        // 设置用户信息
                        commit('setUserInfo', {
                            userName: data.data.userName,
                            userId: data.data.userId,
                            roleType: data.data.roleType
                        })
                    }
                    resolve(res)
                }).catch(err => {
                    reject(err)
                })
            })
        },
        // 退出登录
        handleLogOut ({ state, commit }) {
            logout(state.token)
            return new Promise((resolve, reject) => {
                commit('setToken', '')
                clearAllStorage()
                resolve()
            })
        }
    }
}
